<template>
  <div class="after-sales-container">
    <a-card>
      <!-- 搜索区域 -->
      <div class="search-wrapper">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="订单编号">
            <a-input v-model:value="searchForm.orderId" placeholder="请输入订单编号" />
          </a-form-item>
          <!-- 添加农户ID搜索框，仅管理员可见 -->
          <a-form-item label="农户ID" v-if="userStore.userInfo?.userRole === USER_ROLE.ADMIN">
            <a-input v-model:value="searchForm.farmerId" placeholder="请输入农户ID" />
          </a-form-item>
          <a-form-item label="服务类型">
            <a-select v-model:value="searchForm.serviceType" placeholder="请选择" allowClear>
              <a-select-option v-for="(value, key) in SERVICE_TYPE" :key="value" :value="value">
                {{ SERVICE_TYPE_TEXT[value] }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="服务状态">
            <a-select v-model:value="searchForm.serviceStatus" placeholder="请选择" allowClear>
              <a-select-option v-for="(value, key) in SERVICE_STATUS" :key="value" :value="value">
                {{ SERVICE_STATUS_TEXT[value] }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">搜索</a-button>
              <a-button @click="handleReset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="afterSalesList"
        :loading="loading"
        :pagination="{
          ...pagination,
          showTotal: (total) => `总计 ${total} 条数据`
        }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'serviceType'">
            <a-tag :color="getServiceTypeColor(record.serviceType)">
              {{ getServiceTypeText(record.serviceType) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'serviceStatus'">
            <a-tag :color="getServiceStatusColor(record.serviceStatus)">
              {{ getServiceStatusText(record.serviceStatus) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'createTime'">
            {{ formatDateTime(record.createTime) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleDetail(record)">详情</a-button>
              <a-button
                v-if="record.serviceStatus === 'pending' && userStore.userInfo?.userRole === USER_ROLE.FARMER"
                type="link"
                @click="handleProcess(record)"
              >
                处理
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 售后详情抽屉 -->
    <a-drawer
      v-model:visible="detailVisible"
      title="售后服务详情"
      placement="right"
      width="600"
    >
      <a-descriptions bordered :column="1" style="margin-bottom: 50px">
        <!-- 订单信息 -->
        <a-descriptions-item label="订单信息">
          <div class="order-info">
            <p>订单编号：{{ currentService?.orderId }}</p>
            <p>订单金额：¥{{ currentService?.order?.totalPrice?.toFixed(2) }}</p>
            <p>下单时间：{{ formatDateTime(currentService?.order?.createTime) }}</p>
          </div>
        </a-descriptions-item>

        <!-- 用户信息 -->
        <a-descriptions-item label="用户信息">
          <div class="user-info">
            <p>用户名：{{ currentService?.userName }}</p>
            <p>联系电话：{{ currentService?.order?.user?.phone }}</p>
            <p>收货地址：{{ currentService?.order?.address?.addressName }}</p>
          </div>
        </a-descriptions-item>

        <!-- 商品信息 -->
        <a-descriptions-item label="商品信息">
          <div class="product-info">
            <div class="product-item">
              <img
                :src="currentService?.order?.product?.image"
                class="product-img"
                alt="商品图片"
              />
              <div class="product-detail">
                <div class="product-name">{{ currentService?.order?.product?.name }}</div>
                <div class="product-spec">规格：{{ currentService?.order?.productSKUVO?.quantity }}</div>
                <div class="product-price">
                  <span>¥{{ currentService?.order?.productSKUVO?.price }}</span>
                  <span class="product-quantity">x{{ currentService?.order?.quantity }}</span>
                </div>
              </div>
            </div>
          </div>
        </a-descriptions-item>

        <!-- 售后信息 -->
        <a-descriptions-item label="售后类型">
          <a-tag :color="getServiceTypeColor(currentService?.serviceType)">
            {{ getServiceTypeText(currentService?.serviceType) }}
          </a-tag>
        </a-descriptions-item>

        <a-descriptions-item label="服务状态">
          <a-tag :color="getServiceStatusColor(currentService?.serviceStatus)">
            {{ getServiceStatusText(currentService?.serviceStatus) }}
          </a-tag>
        </a-descriptions-item>

        <a-descriptions-item label="申请原因">
          {{ currentService?.serviceReason }}
        </a-descriptions-item>

        <a-descriptions-item label="申请时间">
          {{ formatDateTime(currentService?.createTime) }}
        </a-descriptions-item>

        <a-descriptions-item label="更新时间">
          {{ formatDateTime(currentService?.updateTime) }}
        </a-descriptions-item>

        <a-descriptions-item label="图片凭证">
          <a-image-preview-group>
            <a-space>
              <a-image
                v-for="(img, index) in currentService?.serviceImages?.split(',')"
                :key="index"
                :src="img"
                :width="100"
              />
            </a-space>
          </a-image-preview-group>
        </a-descriptions-item>

      </a-descriptions>

      <!-- 操作按钮 -->
      <div class="drawer-footer">
        <a-space>
          <a-button @click="detailVisible = false">关闭</a-button>
          <a-button
            v-if="currentService?.serviceStatus === SERVICE_STATUS.PENDING && userStore.userInfo?.userRole === USER_ROLE.FARMER"
            type="primary"
            @click="handleProcess(currentService)"
          >
            处理售后
          </a-button>
        </a-space>
      </div>
    </a-drawer>

    <!-- 处理售后服务弹窗 -->
    <a-modal
      v-model:visible="processVisible"
      title="处理售后服务"
      @ok="handleProcessSubmit"
    >
      <a-form :model="processForm">
        <a-form-item label="处理结果">
          <a-radio-group v-model:value="processForm.serviceStatus">
            <a-radio value="completed">同意</a-radio>
            <a-radio value="rejected">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { formatDateTime } from '@/utils/format'
import {
  SERVICE_TYPE,
  SERVICE_TYPE_TEXT,
  SERVICE_STATUS,
  SERVICE_STATUS_TEXT
} from '@/constants/afterSales'
import { USER_ROLE } from '@/constants/user'
import { useUserStore } from '@/stores/user'
import {
  listAfterSalesServiceVoByPageUsingPost,
  getAfterSalesServiceVoByIdUsingGet,
  updateAfterSalesServiceUsingPost
} from '@/api/afterSalesServiceController'
import { getFarmersVoByUserIdUsingGet } from '@/api/farmersController'

// 获取用户信息
const userStore = useUserStore()

// 搜索表单类型定义
interface SearchForm {
  orderId?: number
  farmerId?: number
  serviceType?: string
  serviceStatus?: string
  current: number
  pageSize: number
}

// 搜索表单
const searchForm = ref<SearchForm>({
  orderId: undefined,
  farmerId: undefined,
  serviceType: undefined,
  serviceStatus: undefined,
  current: 1,
  pageSize: 10
})

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格列定义
const columns = [
  {
    title: '订单编号',
    dataIndex: 'orderId',
    key: 'orderId'
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName'
  },
  {
    title: '服务类型',
    dataIndex: 'serviceType',
    key: 'serviceType'
  },
  {
    title: '服务状态',
    dataIndex: 'serviceStatus',
    key: 'serviceStatus'
  },
  {
    title: '申请时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action'
  }
]

// 状态文本和颜色
const getServiceTypeText = (type: string | undefined) =>
  type ? SERVICE_TYPE_TEXT[type as keyof typeof SERVICE_TYPE_TEXT] : '-'

const getServiceTypeColor = (type: string | undefined) => ({
  [SERVICE_TYPE.RETURN]: 'red',
  [SERVICE_TYPE.EXCHANGE]: 'blue',
  [SERVICE_TYPE.REFUND]: 'orange'
})[type || ''] || 'default'

const getServiceStatusText = (status: string | undefined) =>
  status ? SERVICE_STATUS_TEXT[status as keyof typeof SERVICE_STATUS_TEXT] : '-'

const getServiceStatusColor = (status: string | undefined) => ({
  [SERVICE_STATUS.PENDING]: 'warning',
  [SERVICE_STATUS.PROCESSING]: 'processing',
  [SERVICE_STATUS.COMPLETED]: 'success',
  [SERVICE_STATUS.REJECTED]: 'error'
})[status || ''] || 'default'

// 数据加载
const loading = ref(false)
const afterSalesList = ref([])

// 获取农户ID
const getFarmerId = async () => {
  if (userStore.userInfo?.userRole === USER_ROLE.FARMER && userStore.userInfo?.id) {
    try {
      const res = await getFarmersVoByUserIdUsingGet({
        userId: userStore.userInfo.id
      })
      if (res.data?.id) {
        searchForm.value.farmerId = res.data.id
      }
    } catch (error) {
      console.error('获取农户信息失败', error)
    }
  }
}

const fetchList = async () => {
  loading.value = true
  try {
    const res = await listAfterSalesServiceVoByPageUsingPost({
      ...searchForm.value,
      current: pagination.value.current,
      pageSize: pagination.value.pageSize
    })
    afterSalesList.value = res.data?.records || []
    pagination.value.total = res.data?.total || 0
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  pagination.value.current = 1
  fetchList()
}

const handleReset = () => {
  // 重置时，如果是农户，保留farmerId
  const farmerId = userStore.userInfo?.userRole === USER_ROLE.FARMER ? searchForm.value.farmerId : undefined
  searchForm.value = {
    orderId: undefined,
    farmerId: farmerId,
    serviceType: undefined,
    serviceStatus: undefined,
    current: 1,
    pageSize: 10
  }
  handleSearch()
}

// 表格变化
const handleTableChange = (pag: {current: number, pageSize: number}) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchList()
}

// 详情查看
const detailVisible = ref(false)
const currentService = ref<API.AfterSalesServiceVO>()

const handleDetail = async (record: API.AfterSalesServiceVO) => {
  const res = await getAfterSalesServiceVoByIdUsingGet({ id: record.id })
  currentService.value = res.data as any
  detailVisible.value = true
}

// 处理售后
const processVisible = ref(false)
const processForm = ref({
  id: 0,
  serviceStatus: 'completed'
})

const handleProcess = (record: API.AfterSalesServiceVO) => {
  processForm.value = {
    id: record.id as number,
    serviceStatus: 'completed'
  }
  processVisible.value = true
}

const handleProcessSubmit = async () => {
  try {
    await updateAfterSalesServiceUsingPost(processForm.value)
    message.success('处理成功')
    processVisible.value = false
    fetchList()
    // 如果当前正在查看的详情就是被处理的记录，刷新详情
    if (currentService.value && currentService.value.id === processForm.value.id) {
      handleDetail(currentService.value)
    }
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

onMounted(async () => {
  // 根据用户角色设置查询参数
  await getFarmerId()
  fetchList()
})
</script>

<style scoped>
.after-sales-container {
  padding: 24px;
}

.search-wrapper {
  margin-bottom: 16px;
}

/* 订单信息样式 */
.order-info,
.user-info {
  p {
    margin-bottom: 8px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}

/* 商品信息样式 */
.product-info {
  background: #fafafa;
  padding: 16px;
  border-radius: 4px;
}

.product-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  background: #fff;
  border-radius: 4px;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 12px;
  border-radius: 4px;
}

.product-detail {
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 8px;
}

.product-spec {
  color: #666;
  font-size: 13px;
  margin-bottom: 8px;
}

.product-price {
  color: #ff4d4f;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-quantity {
  color: #666;
  font-size: 13px;
}

/* 抽屉底部按钮 */
.drawer-footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
}

:deep(.ant-descriptions-item-label) {
  width: 100px;
}
</style>
